package com.example.contactcloud;

import java.sql.Timestamp;
import java.util.ArrayList;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Collections;
import java.util.Comparator;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.contactcloud.R;

public class AllContacts extends ListActivity {
	
	static final String EXTRA_MESSAGE="";
	static final String EXTRA_MESSAGE2="";
	
	String loginStatus = "";
	String newlogin = "";
	int groupsSelectedID = 0;
	//SQLITE TIMESTAMP
	Timestamp localTime;
	//MYSQL TIMESTAMP
	Timestamp cloudTime;
	
	private static final String PHP_DUMP = "http://softeng.cs.uwosh.edu/students/baurj00/PHPDump.php";
	private static final String PHP_URL_TIME = "http://softeng.cs.uwosh.edu/students/baurj00/PHPUpdateTime.php";
	private static final String PHP_URL_GET_TIME = "http://softeng.cs.uwosh.edu/students/baurj00/PHPGetTime.php";
	private static final String PHP_UPDATEGROUP = "http://softeng.cs.uwosh.edu/students/baurj00/PHPUpdateGroup.php";
	private static final String PHP_LOAD2 = "http://softeng.cs.uwosh.edu/students/baurj00/PHPLoad2.php";
	private static final String PHP_GET_GROUPS = "http://softeng.cs.uwosh.edu/students/baurj00/PHPGetAllGroups.php";
	private static final String PHP_GET_CONTACTS = "http://softeng.cs.uwosh.edu/students/baurj00/PHPGetAllRows.php";
	private static final String PHP_LOAD_GROUPS = "http://softeng.cs.uwosh.edu/students/baurj00/PHPLoadGroups.php";

	ArrayList<Contact> contacts = new ArrayList<Contact>();
	ArrayList<Group> groups = new ArrayList<Group>();
	
	String currentSearch = "";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setTheme(LoginActivity.globalTheme);
		
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
		Intent i = getIntent();
		loginStatus = i.getStringExtra(EXTRA_MESSAGE);
		
		System.out.println("LOGINSTATUS" + loginStatus);
		
		//Get all contacts from database
		if (!loginStatus.equals("false")){
			new dumpSQLite().execute();
			new updateCloudTimeStamp().execute();
			new AllCloudRowsTask().execute();
		}
		else{
			//Get all contacts from SQLite DB
			new GetAllRowsTask().execute();
			System.out.println("HERE3");
			//Get all groups from SQLite DB
			new GetAllGroupsTask().execute();
			new UpdateTime().execute();
		}
		
		setContentView(R.layout.activity_all_contacts);
		
		
		ImageButton settingsButton = (ImageButton) findViewById(R.id.settingsButton);
		settingsButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v){
				Intent myIntent2 = new Intent(AllContacts.this, EditGroups.class);
				myIntent2.putExtra(EXTRA_MESSAGE, loginStatus);
				startActivityForResult(myIntent2, 0);
			}
		});
		
		ImageButton addContactBtn = (ImageButton) findViewById(R.id.imageButton1);
		addContactBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent myIntent = new Intent(AllContacts.this, AddContact.class); 
				myIntent.putExtra(EXTRA_MESSAGE, loginStatus);
				startActivityForResult(myIntent, 0);
			}
		});
		
		Spinner spinner = (Spinner) findViewById(R.id.groups);
		spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
		    @Override
		    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
		    	Spinner spinner = (Spinner) findViewById(R.id.groups);
		    	groupsSelectedID = spinner.getSelectedItemPosition();
		    	
		    	if (groupsSelectedID == 0){
		    		new GetAllRowsTask().execute();
		    	}
		    	else{
		    		new GetFilteredRowsTask().execute();
		    	}
		    }

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				return;
			}

		});
		
		TextView searchBar = (TextView) findViewById(R.id.search);
		searchBar.addTextChangedListener(new TextWatcher(){

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				Log.d("CM", "Search was for: " + s.toString());
				new SearchContactsTask().execute(s);
			}
			
		});
	}
	
	@Override
	protected void onResume(){
		super.onResume();
		
		Intent i = getIntent();
		
		loginStatus = i.getStringExtra(EXTRA_MESSAGE);
		//Get all contacts from cloud database
		if (!loginStatus.equals("false")){
			new dumpSQLite().execute();
			new AllCloudRowsTask().execute();
			new AllCloudGroupsTask().execute();
		}
		else{
			//Get all contacts from SQLite DB
			new GetAllRowsTask().execute();
			//Get all groups from SQLite DB
			new GetAllGroupsTask().execute();
		}
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.syncWithCloud:
	        	if (loginStatus.equals("false")){
	        		new uploadContacts().execute(this);
	        		new UpdateGroups().execute();
	        		new updateCloudTimeStamp().execute();
	        		Intent myIntent3 = new Intent(AllContacts.this, LoginActivity.class);
	        		myIntent3.putExtra(EXTRA_MESSAGE2, "first");
					startActivityForResult(myIntent3, 0);
					AllContacts.this.finish();
	        	}
	        	else if (!loginStatus.equals("false")){
	        		//if timestamp locally is latest than cloud, then dump cloud mysql DB else dump local SQLite DB
	        		//THEN replace either the local with the cloud db or the cloud with the local db
	        		Context context = getApplicationContext();
	        		CharSequence text = "You are already synced to the cloud!";
	        		int duration = Toast.LENGTH_SHORT;
	        		
	        		Toast toast = Toast.makeText(context, text, duration);
	        		toast.show();
	        	}
	        
	        	return true;	
	        case R.id.editTheme:
	        	Intent myIntent3 = new Intent(AllContacts.this, ChangeTheme.class);
				startActivityForResult(myIntent3, 0);
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	@Override
	public void onListItemClick(ListView list, View view, int position, long id) {
		super.onListItemClick(list, view, position, id);
		Contact a = (Contact) list.getAdapter().getItem(position);
		try {
			Intent intent = new Intent(this, ViewContacts.class);
			intent.putExtra(EXTRA_MESSAGE, loginStatus);
			intent.putExtra("Contact", a);
			startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	// Inflate the menu; this adds items to the action bar if it is present.
	getMenuInflater().inflate(R.menu.options_menu, menu);
	return true;
	}
	
	@Override
	protected void onActivityResult (int requestCode, int resultCode, Intent data){
		if(requestCode == 1){
			new GetAllRowsTask().execute();
		}
	}
	
	public class GetAllRowsTask extends AsyncTask<Void, Integer, ArrayList<Contact>>{

		@Override
		protected ArrayList<Contact> doInBackground(Void... nothing) {
			
			ContactsDataSource cds = new ContactsDataSource(AllContacts.this);
			
			cds.open();

			ArrayList<Contact> contacts = cds.getAllContacts();
			
			cds.close();
			
			Collections.sort(contacts, new Comparator<Contact>(){
				public int compare(Contact c1, Contact c2) {
		               return c1.getName().compareToIgnoreCase(c2.getName());
		            }
			});

			return contacts;
		}
		
        @Override
        protected void onPostExecute(ArrayList<Contact> contactList) {
            setListAdapter(new ArrayAdapter<Contact>(AllContacts.this, android.R.layout.simple_list_item_1, contactList));
            AllContacts.this.contacts = contactList;
        }
		
	}
	
	private class GetFilteredRowsTask extends AsyncTask<Void, Integer, ArrayList<Contact>>{

		@Override
		protected ArrayList<Contact> doInBackground(Void... nothing) {
			
			ContactsDataSource cds = new ContactsDataSource(AllContacts.this);
			
			cds.open();
			ArrayList<Contact> contacts = cds.getContactsGroup(groupsSelectedID);
			
			cds.close();
			
			Collections.sort(contacts, new Comparator<Contact>(){
				public int compare(Contact c1, Contact c2) {
		               return c1.getName().compareToIgnoreCase(c2.getName());
		            }
			});

			return contacts;
		}
		
        @Override
        protected void onPostExecute(ArrayList<Contact> contactList) {
            setListAdapter(new ArrayAdapter<Contact>(AllContacts.this, android.R.layout.simple_list_item_1, contactList));
            AllContacts.this.contacts = contactList;
        }
		
	}
	
	//Get SQLITE TimeStamp
	private class getTime extends AsyncTask<Void, Integer, Timestamp>{
		@Override
		protected Timestamp doInBackground(Void... nothing) {
			
			Timestamp time;
			
			ContactsDataSource cds2 = new ContactsDataSource(AllContacts.this);
			
			cds2.open();
			
			time = cds2.getTime();
			
			System.out.println("LOCALTIME OOOOOOOOOOOO   " + time);
			
			AllContacts.this.localTime = time; 
			
			System.out.println(AllContacts.this.localTime);
			
			cds2.close();
			
			return localTime;
		}
		
		@Override
        protected void onPostExecute(Timestamp time) {
    		time = AllContacts.this.cloudTime;
        }
		
	}
	
	private class SearchContactsTask extends AsyncTask<CharSequence, Integer, ArrayList<Contact>>{

		@Override
		protected ArrayList<Contact> doInBackground(CharSequence... searchChars) {
			ArrayList<Contact> search = new ArrayList<Contact>();
			
			for(Contact c : AllContacts.this.contacts){
				if(c.getName().toLowerCase().contains(searchChars[0].toString().toLowerCase()) || searchChars.toString().equals("")){
					search.add(c);
					Log.d("CM", c.getName() + " " + c.getGroup());
				}
			}
			return search;
		}
		
        @Override
        protected void onPostExecute(ArrayList<Contact> contactList) {
            setListAdapter(new ArrayAdapter<Contact>(AllContacts.this, android.R.layout.simple_list_item_1, contactList));        
        }
		
	}
	
	
	
	public class GetAllGroupsTask extends AsyncTask<Void, Integer, ArrayList<Group>>{

		@Override
		protected ArrayList<Group> doInBackground(Void... nothing) {
			
			ContactsDataSource cds2 = new ContactsDataSource(AllContacts.this);
			
			cds2.open();
			
			ArrayList<Group> groups = cds2.getAllGroups();
			
			cds2.close();
			
			return groups;
		}
		
        @Override
        protected void onPostExecute(ArrayList<Group> groupList) {
    		Spinner spinner = (Spinner) findViewById(R.id.groups);
    		ArrayAdapter<Group> adapter =  new ArrayAdapter<Group>(AllContacts.this, android.R.layout.simple_spinner_dropdown_item, groupList);
    		spinner.setAdapter(adapter);
        }
		
	}
	
	/**
	 * Represents an asynchronous getAllRows task to return an arraylist of all contact objects
	 */
	public class AllCloudRowsTask extends AsyncTask<Void, Integer, ArrayList<Contact>> {
		@Override
		protected ArrayList<Contact> doInBackground(Void... params) {

			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
			
			ArrayList<Contact> cList = new ArrayList<Contact>();
			
			if(networkInfo != null && networkInfo.isConnected())
			{	
				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(PHP_GET_CONTACTS);
				
				try
				{
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					String response = httpClient.execute(httppost, respondHandler);
					System.out.println(response);

					//Parse JSON Data
					String id = "";
					String name = "";
					String cell = "";
					String alt = "";
					String address = "";
					String email = "";
					String comments = "";
					String groupsid = "";

					try{

						JSONArray jArray = new JSONArray(response);
						
						JSONObject json_data = null;

						for(int i = 0; i < jArray.length(); i++)
						{
							json_data = jArray.getJSONObject(i);
							
							id = json_data.getString("id");
							name = json_data.getString("name");
							cell = json_data.getString("cell");
							alt = json_data.getString("alt");
							address = json_data.getString("address");
							email = json_data.getString("email");
							comments = json_data.getString("comments");
							groupsid = json_data.getString("groupsid");
							Contact contactTemp = new Contact(Long.valueOf(id), name, address, cell, alt, email, comments, Integer.parseInt(groupsid));
							cList.add(contactTemp);
						}
						
					}catch(JSONException e1){
						e1.printStackTrace();
					}catch (ParseException e1){
						e1.printStackTrace();
					}
						
				}
				catch(Exception e){
					
				}
			}		
			return cList;
			
		}

        @Override
        protected void onPostExecute(ArrayList<Contact> contactList) {
        	new AddContactTask().execute(contactList);
        }
	}
	
	/**
	 * Represents an asynchronous getAllRows task to return an arraylist of all group objects
	 */
	public class AllCloudGroupsTask extends AsyncTask<Void, Integer, ArrayList<Group>> {
		@Override
		protected ArrayList<Group> doInBackground(Void... params) {

			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
			
			ArrayList<Group> gList = new ArrayList<Group>();
			
			if(networkInfo != null && networkInfo.isConnected())
			{	
				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(PHP_GET_GROUPS);
				
				try
				{
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					String response = httpClient.execute(httppost, respondHandler);
					System.out.println(response);

					//Parse JSON Data
					String groupname = "";
					
					try{

						JSONArray jArray = new JSONArray(response);
						
						JSONObject json_data = null;

						for(int i = 0; i < jArray.length(); i++)
						{
							json_data = jArray.getJSONObject(i);
							
							groupname = json_data.getString("groupname");
							Group tempGroup = new Group(i, groupname);
							gList.add(tempGroup);
						}
						
					}catch(JSONException e1){
						e1.printStackTrace();
					}catch (ParseException e1){
						e1.printStackTrace();
					}
						
				}
				catch(Exception e){
					System.out.println("UPLOAD GROUPS FAIL");
				}
			}		
			return gList;
			
		}

        @Override
        protected void onPostExecute(ArrayList<Group> groupList) {
    		Spinner spinner = (Spinner) findViewById(R.id.groups);
    		ArrayAdapter<Group> adapter =  new ArrayAdapter<Group>(AllContacts.this, android.R.layout.simple_spinner_dropdown_item, groupList);
    		spinner.setAdapter(adapter);
        }
	}
	
	
	
	private class AddGroupTask extends AsyncTask<Object, Context, String>{

		@Override
		protected String doInBackground(Object... params) {
			
			@SuppressWarnings("unchecked")
			ArrayList<Group> g = (ArrayList<Group>) params[0];
			
			ContactsDataSource cds = new ContactsDataSource(AllContacts.this);
			
			cds.open();
			
			for(int i = 0; i < g.size(); i++)
			{
				cds.addGroup(g.get(i));
			}
			
			cds.close();
			
			return "";
		}

        @Override
        protected void onPostExecute(String t) 
        {
        		new GetAllGroupsTask().execute();
        }
	}
	
	private class AddContactTask extends AsyncTask<Object, Context, String>{

		@Override
		protected String doInBackground(Object... params) {
			
			@SuppressWarnings("unchecked")
			ArrayList<Contact> c = (ArrayList<Contact>) params[0];
			
			ContactsDataSource cds = new ContactsDataSource(AllContacts.this);
			
			cds.open();
			try{
				for(int i = 0; i < c.size(); i++)
				{
					cds.addContact(c.get(i));
				}
			}
			catch(Exception e){
				System.out.println("Failed to add");
			}
			
			cds.close();
			
			return "";
		}

        @Override
        protected void onPostExecute(String t) 
        {
        		new GetAllRowsTask().execute();
        }
	}
	
	private class updateCloudTimeStamp extends AsyncTask<Void, Integer, Void>{

			@Override
			protected Void doInBackground(Void... params) {
				ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
				
				if(networkInfo != null && networkInfo.isConnected())
				{
					
					HttpClient httpClient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost(PHP_URL_TIME);
					
					try
					{
						ResponseHandler<String> respondHandler = new BasicResponseHandler();
						String response = httpClient.execute(httppost, respondHandler);
		
					}
					catch(Exception e){
						
					}
				}
			
			return null;
		}
	
	}
	
	//Delete mysql DB
	
	private class dumpMySQL extends AsyncTask<Void, Integer, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
			
			if(networkInfo != null && networkInfo.isConnected())
			{
				
				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(PHP_DUMP);
				
				try
				{
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					String response = httpClient.execute(httppost, respondHandler);
	
				}
				catch(Exception e){
					
				}
			}
		
		return null;
	}

}
	
	//Dump SQLite DB
	private class dumpSQLite extends AsyncTask<Void, Integer, Void>{

		@Override
		protected Void doInBackground(Void... nothing) {
			
			ContactsDataSource cds2 = new ContactsDataSource(AllContacts.this);
			
			cds2.open();
			
			try {
				cds2.deleteAllRows();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			cds2.close();
			
			return null;
		}

	}
	

	//Get MYSQL Time Stamp
	
	public class getCloudTimeTask extends AsyncTask<Void, Void, Timestamp> {
		
		
		@Override
		protected Timestamp doInBackground(Void... params) {

			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
			Timestamp time1;
			
			if(networkInfo != null && networkInfo.isConnected())
			{

				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(PHP_URL_GET_TIME);
				
				try
				{
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					String response = httpClient.execute(httppost, respondHandler);
					
					//Parse JSON Data
					String time=null;
					try{
						
						JSONArray jArray = new JSONArray(response);
						JSONObject json_data=null;
						json_data = jArray.getJSONObject(0);
						time = json_data.getString("time");
						
						time1 = Timestamp.valueOf(time);
						
						AllContacts.this.cloudTime = time1;
						
			      	
					}catch(JSONException e1){
						System.out.println("FAIL1");
						e1.printStackTrace();
					}catch (ParseException e1){
						System.out.println("FAIL2");
						e1.printStackTrace();
					}
				}
				catch(Exception e){
					System.out.println("FAIL3");
				}
			}
			
			return AllContacts.this.cloudTime;
		}
		
		@Override
        protected void onPostExecute(Timestamp time) {
    		time = AllContacts.this.cloudTime;
        }

	}
	
	private class UpdateTime extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			
			ContactsDataSource cds = new ContactsDataSource(AllContacts.this);
			
			cds.open();
			
			cds.updateTime();
			
			cds.close();
			return null;
		}

		
	}
	
	public class uploadContacts extends AsyncTask<Context, Void, String> 
	{
		@Override
		protected String doInBackground(Context... arg0) 
		{
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
			
			if(networkInfo != null && networkInfo.isConnected())
			{
				ContactsDataSource cds = new ContactsDataSource(arg0[0]);
				cds.open();
				ArrayList<Contact> allContacts = cds.getAllContacts();
				cds.close();
				
				JSONArray allJSONContacts = new JSONArray();
				
				String all2 = null;
				
				for(int i = 0; i < allContacts.size(); i++)
				{
					JSONObject jContact = new JSONObject();
					Contact temp = allContacts.get(i);
					try
					{
						jContact.put("name", temp.getName());
						jContact.put("address", temp.getAddress());
						jContact.put("cell", temp.getCell());
						jContact.put("alt", temp.getAlt());
						jContact.put("email", temp.getEmail());
						jContact.put("comments", temp.getComments());
						jContact.put("group", temp.getGroup());
						allJSONContacts.put(i, jContact);				
					}catch(Exception ex)
					{
						System.err.println("Cannot create #" + i + " JSON Contact");
					}
				}
				
				all2 = allJSONContacts.toString();
				
				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(PHP_LOAD2);
 				
				ArrayList<NameValuePair> c = new ArrayList<NameValuePair>(1);
				c.add(new BasicNameValuePair("json", all2));
				
				try
				{				
					httppost.setEntity(new UrlEncodedFormEntity(c));
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					String rep = httpClient.execute(httppost, respondHandler);
				}
				catch(Exception e){
					System.out.println(e.getMessage() + "PHP ERROR");
				}
			}
		
			return "";
		}
		
        @Override
        protected void onPostExecute(String t) 
        {
        	if (loginStatus.equals("false")){
        		new dumpSQLite().execute();
        	}
        }

	}
	
	private class UpdateGroups extends AsyncTask<Void, Void, Boolean> 
	{
		@Override
		protected Boolean doInBackground(Void... arg0) 
		{
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
			
			if(networkInfo != null && networkInfo.isConnected())
			{
				ContactsDataSource cds = new ContactsDataSource(AllContacts.this);
				cds.open();
				ArrayList<Group> allGroups = cds.getAllGroups();
				cds.close();
			
				
				JSONArray allJSONGroups = new JSONArray();
				
				String all = null;
				
				for(int i = 0; i < allGroups.size(); i++)
				{
					JSONObject jGroup = new JSONObject();
					Group temp = allGroups.get(i);
					try
					{
						jGroup.put("groupid", temp.getGroupId());
						jGroup.put("groupname", temp.getGroupName());		
						allJSONGroups.put(i, jGroup);	
					}catch(Exception ex)
					{
						System.err.println("Cannot update #" + i + " JSON Group");
					}
				}
				
				all = allJSONGroups.toString();
				
				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(PHP_UPDATEGROUP);
 				
				ArrayList<NameValuePair> c = new ArrayList<NameValuePair>(1);
				c.add(new BasicNameValuePair("json", all));
				
				try
				{				
					httppost.setEntity(new UrlEncodedFormEntity(c));
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					String rep = httpClient.execute(httppost, respondHandler);
				}
				catch(Exception e){
					System.out.println(e.getMessage() + "FAIL");
				}
			}
		
			return null;
		}

	}
	
	//TODO upload latest LOADGroups PHP file
	public class uploadGroups extends AsyncTask<Context, Void, Boolean> 
	{
		@Override
		protected Boolean doInBackground(Context... arg0) 
		{
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
			
			if(networkInfo != null && networkInfo.isConnected())
			{
				ContactsDataSource cds = new ContactsDataSource(arg0[0]);
				cds.open();
				ArrayList<Group> allGroups = cds.getAllGroups();
				cds.close();
				
				JSONArray allJSONGroups = new JSONArray();
				
				String all = null;
				
				for(int i = 0; i < allGroups.size(); i++)
				{
					JSONObject jGroup = new JSONObject();
					Group temp = allGroups.get(i);
					try
					{
						jGroup.put("groupname", temp.getGroupName());
						jGroup.put("groupid", temp.getGroupId());
						allJSONGroups.put(i, jGroup);
					}catch(Exception ex)
					{
						System.err.println("Cannot create #" + i + " JSON Group");
					}
				}
				
				all = allJSONGroups.toString();
				
				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(PHP_LOAD_GROUPS);
 				
				ArrayList<NameValuePair> c = new ArrayList<NameValuePair>(1);
				c.add(new BasicNameValuePair("json", all));
				
				try
				{				
					httppost.setEntity(new UrlEncodedFormEntity(c));
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					String rep = httpClient.execute(httppost, respondHandler);
				}
				catch(Exception e){
					System.out.println(e.getMessage());
					System.out.println("ALLGROUPS");
				}
			}
		
			return null;
		}

	}

}

